/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gui;

import java.awt.event.KeyEvent;
import java.beans.PropertyVetoException;
import javax.annotation.PostConstruct;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import org.app.controller.SpiderCrawlsAction;

/**
 *
 * @author LamLe
 */
public class AutoDownloadMovieGUI extends javax.swing.JFrame {

    private static Logger logger = Logger.getLogger(AutoDownloadMovieGUI.class);
    /**
     * Creates new form AutoDownloadMovieGUI
     */
    private String HINT = "Type movie name and press \"Enter\"";
    private boolean running = false;
    private SpiderCrawlsAction spider = null;

    @PostConstruct
    public void init() {
        initComponents();
        customGUI();
        initConfig();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        desktopPane = new javax.swing.JDesktopPane();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        jPanel1 = new javax.swing.JPanel();
        txtSearch = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtaResult = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        helpMenu = new javax.swing.JMenu();
        clearMenu = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Auto Download Movie");

        jInternalFrame1.setTitle("Search form");
        jInternalFrame1.setVisible(true);

        jPanel1.setBackground(new java.awt.Color(153, 255, 255));

        txtSearch.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        txtSearch.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtSearchFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtSearchFocusLost(evt);
            }
        });
        txtSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtSearchKeyPressed(evt);
            }
        });

        txtaResult.setEditable(false);
        txtaResult.setColumns(20);
        txtaResult.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtaResult.setRows(5);
        jScrollPane1.setViewportView(txtaResult);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtSearch, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                .addGap(41, 41, 41))
        );

        jInternalFrame1.getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        jInternalFrame1.setBounds(0, 0, 390, 260);
        desktopPane.add(jInternalFrame1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        fileMenu.setIcon(new javax.swing.ImageIcon("resources\\exit.png"));
        fileMenu.setMnemonic('f');
        fileMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                fileMenuMousePressed(evt);
            }
        });
        menuBar.add(fileMenu);

        helpMenu.setIcon(new javax.swing.ImageIcon("resources\\info.png"));
        helpMenu.setMnemonic('h');
        helpMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                helpMenuMousePressed(evt);
            }
        });
        menuBar.add(helpMenu);

        clearMenu.setIcon(new javax.swing.ImageIcon("resources\\edit-clear.png"));
        clearMenu.setMnemonic('f');
        clearMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                clearMenuMousePressed(evt);
            }
        });
        menuBar.add(clearMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtSearchKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSearchKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            lock();
            Thread t = new Thread(new SpiderCrawlsAction(this));
            t.start();
        }
    }//GEN-LAST:event_txtSearchKeyPressed

    private void txtSearchFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtSearchFocusGained
        if (txtSearch.getText().equals(HINT)) {
            txtSearch.setText("");
        }
    }//GEN-LAST:event_txtSearchFocusGained

    private void txtSearchFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtSearchFocusLost
        if (txtSearch.getText().equals("")) {
            txtSearch.setText(HINT);
        }
    }//GEN-LAST:event_txtSearchFocusLost

    private void fileMenuMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileMenuMousePressed
        System.exit(0);
    }//GEN-LAST:event_fileMenuMousePressed

    private void helpMenuMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_helpMenuMousePressed
        JOptionPane.showMessageDialog(this, " Author : Ngọc Lâm  © 2013 \n version 0.0.2 . Release date : 2013/06/18", "About", JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_helpMenuMousePressed

    private void clearMenuMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearMenuMousePressed
        if (running) {
            JOptionPane.showMessageDialog(this, "Your application is running, please wait !!!");
        } else {
            txtaResult.setText("");
        }
    }//GEN-LAST:event_clearMenuMousePressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AutoDownloadMovieGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AutoDownloadMovieGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AutoDownloadMovieGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AutoDownloadMovieGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AutoDownloadMovieGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu clearMenu;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextArea txtaResult;
    // End of variables declaration//GEN-END:variables

    private void customGUI() {
        try {
            jInternalFrame1.setMaximum(true);
            this.setExtendedState(JFrame.MAXIMIZED_BOTH);
            txtSearch.setText(HINT);

            txtaResult.setWrapStyleWord(true);
            txtaResult.setLineWrap(true);
        } catch (PropertyVetoException ex) {
            logger.error(ex.toString());
        } catch (Exception e) {
            logger.error(e.toString());
        }
    }

    private void initConfig() {
    }

    public String getMovieName() {
        return txtSearch.getText();
    }

    public synchronized void write(final String text) {
        Runnable runnable = new Runnable() {
            public void run() {
                if (text != null) {
                    logger.info(text);
                    txtaResult.append(text);
                    txtaResult.append("\n");
                    txtaResult.setCaretPosition(txtaResult.getDocument().getLength());
                }
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    public void lock() {
        Runnable runnable = new Runnable() {
            public void run() {
                running = true;
                txtSearch.setEditable(false);
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    public void unlock() {
        Runnable runnable = new Runnable() {
            public void run() {
                running = false;
                txtSearch.setEditable(true);
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}
